package cn.zxh.improvement.auth.security.authentication.admin.password;

import cn.zxh.improvement.auth.security.model.PasswordLoginRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录处理
 */
public class AdminPasswordLoginProcessFilter extends AbstractAuthenticationProcessingFilter {
    protected AdminPasswordLoginProcessFilter(AuthenticationManager authenticationManager) {
        super("admin/auth/passLogin", authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        PasswordLoginRequest loginRequest = objectMapper.readValue(request.getInputStream(), PasswordLoginRequest.class);
        AdminPasswordToken passwordToken = new AdminPasswordToken(loginRequest.getUsername(), loginRequest.getPwd());
        return this.getAuthenticationManager().authenticate(passwordToken);
    }
}
